<template>
  <el-card class="container-card">
    <el-button type="primary" @click="showAddTrademark">新增</el-button>
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      class="container-table"
    >
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="匹配LOGO" prop="logoUrl">
        <template v-slot="{ row }">
          <img class="trademark-img" :src="row.logoUrl" :alt="row.tmName">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            @click="showUpdateTrademark(row)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="delTrademark(row
            )"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[3, 6, 9, 12]"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, total, sizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="`${idUpdateTrademark ? '修改' : '添加'}品牌`"
      :visible.sync="visible"
    >
      <el-form ref="form" :rules="rules" :model="trademark" label-width="100px">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademark.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseAPI}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/jpeg,image/png,image/jpg"
          >
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar el-upload"
            >
            <i v-else class="el-upload el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="addTrademark">确定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqTrademarkList,
  reqAddTrademark,
  reqDelTrademark,
  reqUpdateTrademark
} from '@/api/product/trademark'
export default {
  name: 'Trademark',
  data() {
    return {
      currentPage: 1,
      pageSize: 3,
      total: 10,
      trademarkList: [],
      loading: false,
      visible: false,
      baseAPI: process.env.VUE_APP_BASE_API,
      trademark: {
        tmName: '',
        logoUrl: ''
      },
      idUpdateTrademark: false,
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请上传品牌LOGO', trigger: 'change' }
        ]
      }
    }
  },
  async mounted() {
    this.getTrademarkList(this.currentPage, this.pageSize)
  },
  methods: {
    async getTrademarkList(currentPage, pageSize) {
      this.loading = true
      const data = await reqTrademarkList(currentPage, pageSize)
      this.trademarkList = data.records
      this.total = data.total
      this.loading = false
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getTrademarkList(this.currentPage, pageSize)
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getTrademarkList(currentPage, this.pageSize)
    },
    handleAvatarSuccess(res) {
      this.trademark.logoUrl = res.data
      this.$refs.form.clearValidate(['logoUrl'])
    },
    beforeAvatarUpload(file) {
      const fileType = ['image/jpeg', 'image/png', 'image/jpg']
      const isValidateType = fileType.indexOf(file.type) > -1

      const isValidateSize = file.size / 1024 < 500

      if (!isValidateType) {
        this.$message.error('上传品牌图片只能是 JPG 或 PNG 格式!')
      }
      if (!isValidateSize) {
        this.$message.error('上传品牌图片大小不能超过 500KB!')
      }
      return isValidateType && isValidateSize
    },
    async showAddTrademark() {
      this.visible = true
      this.isUpdateTrademark = false
      this.$refs.form?.resetFields()
      this.trademark = { tmName: '', logoUrl: '' }
    },
    async showUpdateTrademark(tm) {
      this.visible = true
      this.isUpdateTrademark = true
      this.trademark = { ...tm }
    },
    async addTrademark() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.isUpdateTrademark) {
            await reqUpdateTrademark(this.trademark)
          } else {
            await reqAddTrademark(this.trademark)
          }
          this.$message({
            type: 'success',
            message: `${this.isUpdateTrademark ? '修改' : '添加'}品牌成功`
          })
          this.visible = false
          this.getTrademarkList(this.currentPage, this.pageSize)
        }
      })
    },
    delTrademark(tm) {
      this.$confirm(
        `确定删除<span style="color:red">${tm.tmName}</span>品牌?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(async() => {
        await reqDelTrademark(tm.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        if (this.trademarkList.length === 1 && this.currentPage > 1) {
          this.currentPage--
        }
        this.getTrademarkList(this.currentPage, this.pageSize)
      })
    }
  }
}
</script>

<style lang="sass" scoped>
.trademark-img
  width:100px
  height:100px

.avatar-uploader .el-upload
  border: 1px dashed #d9d9d9
  border-radius: 6px
  cursor: pointer
  position: relative
  overflow: hidden

  &:hover
    border-color: #409EFF

  .avatar-uploader-icon
    font-size: 28px
    color: #8c939d
    width: 178px
    height: 178px
    line-height: 178px
    text-align: center
  .avatar
    width: 178px
    height: 178px
    display: block
</style>
